<template>
  <!-- 管理员布局 -->
  <el-container v-if="isAdmin" class="admin-layout">
    <!-- 左侧边栏 -->
    <ManageSider />

    <!-- 右侧内容区 -->
    <el-container direction="vertical">
      <!-- 顶部导航栏 -->
      <ManageHeader v-if="showHeader"/>

      <!-- 主内容区 -->
      <el-main class="admin-main-content">
        <div class="admin-container">
          <h1>个人信息管理</h1>

          <!-- 用户信息展示 -->
          <el-descriptions :column="1" border v-if="userInfo">
            <el-descriptions-item label="用户ID">{{ userInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ userInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.telephone }}</el-descriptions-item>
            <el-descriptions-item label="用户类型">
              <el-tag :type="userInfo.type === null ? 'success' : ''">
                {{ userInfo.type  }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatDate(userInfo.date) }}</el-descriptions-item>
          </el-descriptions>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button
                type="primary"
                @click="showEditDialog"
            >
              编辑信息
            </el-button>
            <el-button
                type="danger"
                @click="handleLogout"
            >
              退出登录
            </el-button>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 普通用户布局 -->
  <div v-else>
    <NormalHeader />
    <div class="permission-denied">
      <h1>管理员功能暂时不对您开放</h1>
    </div>
  </div>

  <!-- 修改用户信息的弹框 -->
  <el-dialog v-model="editDialogVisible" title="修改个人信息" width="30%">
    <el-form :model="editForm" label-width="80px" :rules="rules" ref="editForm">
      <el-form-item label="用户名" prop="name">
        <el-input v-model="editForm.name" />
      </el-form-item>
<!--      <el-form-item label="手机号" prop="telephone">-->
<!--        <el-input v-model="editForm.telephone" />-->
<!--      </el-form-item>-->
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="editForm.password" show-password />
      </el-form-item>
<!--      <el-form-item label="确认密码" prop="confirmPassword">-->
<!--        <el-input type="password" v-model="editForm.confirmPassword" show-password />-->
<!--      </el-form-item>-->
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditForm">保存</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import { GetUserInfo, UpdateUserInfo, LogOut } from "@/api";
import dayjs from 'dayjs';
import NormalHeader from "@/components/NormalHeader.vue";
import ManageSider from "@/components/ManageSider.vue";
import ManageHeader from "@/components/ManageHeader.vue";

export default {
  name: "ManageInfo",
  components: {
    NormalHeader,
    ManageSider,
    ManageHeader
  },

  data() {
    const validatePassword = (rule, value, callback) => {
      if (this.editForm.password && value !== this.editForm.password) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };

    return {
      isAdmin: false,
      userInfo: null,
      editDialogVisible: false,
      showHeader: true,
      // showHeader,
      // fetchUserInfo,
      editForm: {
        name: '',
        telephone: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    };
  },
  async mounted() {
    await this.checkAdminPermission();
    await this.fetchUserInfo();
  },
  methods: {
    async checkAdminPermission() {
      const userType = localStorage.getItem("type");
      this.isAdmin = userType === "0";
    },
    async fetchUserInfo() {
      try {
        const { data } = await GetUserInfo();
        if (data.code === 200) {
          this.userInfo = data.data;
          this.editForm.name = data.data.name;
          this.editForm.telephone = data.data.telephone;
        } else {
          ElMessage.error(data.message || "获取用户信息失败");
        }
      } catch (error) {
        ElMessage.error("获取用户信息失败");
        console.error(error);
      }
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    },
    showEditDialog() {
      this.editDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.editForm?.clearValidate();
      });
    },
    async submitEditForm() {
      try {
        await this.$refs.editForm.validate();

        const updateData = {
          name: this.editForm.name,
          // telephone: this.editForm.password
        };

        if (this.editForm.password) {
          updateData.password = this.editForm.password;
        }

        const { data } = await UpdateUserInfo(updateData);

        if (data.code === 200) {
          ElMessage.success("修改成功");
          localStorage.setItem('username', this.editForm.name);
          await this.fetchUserInfo();
          this.editDialogVisible = false;
          localStorage.setItem('username', this.editForm.name);
        } else {
          ElMessage.error(data.message || "修改失败");
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error("修改失败:", error);
        }
      }
      this.showHeader = false;
      setTimeout(() => {
        this.fetchUserInfo(); // 页面加载时自动调用
        this.showHeader = true;
      }, 10)
    },
    async handleLogout() {
      try {
        await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const token = localStorage.getItem('token');
        if (token) {
          await LogOut(token);
        }

        localStorage.removeItem('token');
        localStorage.removeItem('type');
        localStorage.removeItem('username');
        this.$router.push('/login');
        ElMessage.success("已退出登录");
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error("退出登录失败");
        }
      }
    }
  }
};
</script>

<style scoped>
.admin-layout {
  height: 100vh;
}

.admin-main-content {
  padding: 20px;
  height: 100vh;
  overflow-y: auto;
  margin-left: 200px; /* 等于侧边栏宽度 */
  background-color: #f5f7fa;
}

.admin-container {
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.permission-denied {
  text-align: center;
  padding: 100px 0;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .admin-container {
    padding: 20px;
  }

  .admin-main-content {
    margin-left: 0;
  }

  .action-buttons {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
